package com.example.courseselectionsystemconsume.listener;

//import com.example.courseselectionsystemconsume.service.impl.UserServiceImpl;
import com.example.courseselectionsystemconsume.pojo.MyAddress;
import com.example.courseselectionsystemconsume.pojo.User;
import com.example.courseselectionsystemconsume.service.MailService;
import com.example.courseselectionsystemconsume.service.impl.UserServiceImpl;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.annotation.Resource;

/**
 * @description: TODO
 * @author: Tokyo_God
 * @date: 2020/12/27 21:15
 * Role of:
 * @version: v1.0
 */
@Component
public class TopicListener {

    @Resource
    UserServiceImpl userService;

    @Resource
    MailService mailService;
    @Resource(name = "myAddress")
    MyAddress myAddress;

    @Autowired
    private TemplateEngine engine;
                                //register-topic
    @JmsListener(destination = "${registerTopic}",containerFactory =
            "jmsListenerContainerTopic")
    public void RegisterListener(String userJson) {
        /*TextMessage textMessage= (TextMessage) message;*/
        /*System.out.println(userJson);*/

        JSONObject jsonObject =JSONObject.fromObject(userJson);
        User user= (User) JSONObject.toBean(jsonObject,User.class);
        //注邮箱添加了唯一约束
        System.out.println("生产者传过来的json:"+userJson);
        userService.register(user);//添加用户

        /*InetAddress address= null;
        try {
            address = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        String path="127.0.0.1";
        if(address!=null){
            path=address.getHostAddress();
        }*/

        System.out.println("消费者监听器拿去到的IP地址address:"+myAddress.getAddress());
        //发送邮件
        Context context=new Context();
        context.setVariable("name",user.getName());
        context.setVariable("sex",user.getSex());
        context.setVariable("address",myAddress.getAddress());/////////////////////////////////////////////////////
        //调用 thymeleaf架包里的方法
        //指定文件email.html   且设置属性name=‘杜赖’以方便email那边调用
        String content=engine.process("activate",context);
        mailService.sendHtmlMail(user.getEmail(),"激活邮箱",content);

    }

    
}
